<?php

namespace App\Admin\Controllers;

use App\Admin\Widgets\InfoBox;
use App\Http\Controllers\Controller;
use App\Models\CurveOrderRecord;
use App\Models\FlowChannelStat;
use App\Models\Order;
use App\Models\OrderReadInfo;
use App\Models\VisitRecord;
use Carbon\Carbon;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Table;
use Illuminate\Support\Facades\Redis;

class HomeController extends Controller
{
    public function index(Content $content)
    {
        $redis = Redis::connection();
        return $content
            ->title('首页')
            ->description(Carbon::now()->toDateTimeString().'接口剩余次数：'.$redis->get('count'))
            ->row(function (Row $row) {

                $row->column(3, function (Column $column) {

                    $today_pv = FlowChannelStat::query()->whereDate('date', Carbon::now()->toDateString())->sum('pv');
                    $redis = Redis::connection();
                    $expect_read_num = 0;
                    $curve_order_list = $redis->zrange('curve_order_list', 0, -1);

                    foreach ($curve_order_list as $curve_order) {
                        $expect_read_num += $redis->hget($curve_order, 'expect_read_num');
                    }
                    $card = new InfoBox('今日PV', '', 'green', null, $today_pv, '5分钟期望PV：' . $expect_read_num);
                    $column->append($card);
                });

                $row->column(3, function (Column $column) {
                    $today_ip = FlowChannelStat::query()->whereDate('date', Carbon::now()->toDateString())->sum('ip_num');

                    $card = new InfoBox('今日IP', '', 'orange', null, $today_ip);
                    $column->append($card);
                });


                $row->column(3, function (Column $column) {
                    $daoda_rate = FlowChannelStat::query()->whereDate('date', Carbon::now()->toDateString())->selectRaw('sum(read_num_incr)/sum(pv) as daoda_rate')->first();
                    $card = new InfoBox('到达率', '', 'red', null, round($daoda_rate->daoda_rate, 2) * 100 . '%');
                    $column->append($card);
                });

                $row->column(3, function (Column $column) {
                    $order_on_num = Order::query()->where('state', Order::ORDER_STATE_ON)->count();

//                    $headers = ['订单类型', '时速'];
                    $common_order_speed = OrderReadInfo::query()->where([
                        'date' => Carbon::now()->toDateString(),
                    ])->whereBetween('hour', [Carbon::now()->subHour()->hour, Carbon::now()->hour])
                        ->whereHas('order', function ($order) {
                            $order->where('type', Order::ORDER_TYPE_COMMON);
                        })->selectRaw('sum(read_num_inc) as read_num_inc,count(distinct order_id) as order_num')
                        ->first();
                    $curve_order_speed = OrderReadInfo::query()->where([
                        'date' => Carbon::now()->toDateString()
                    ])->whereBetween('hour', [Carbon::now()->subHour()->hour, Carbon::now()->hour])
                        ->whereHas('order', function ($order) {
                            $order->where('type', Order::ORDER_TYPE_CURVE);
                        })->selectRaw('sum(read_num_inc) as read_num_inc,count(distinct order_id) as order_num')
                        ->first();
                    $rows = [
                        [
                            '普通快单时速', intval($common_order_speed->read_num_inc / $common_order_speed->order_num)
                        ],
                        [
                            '曲线单时速', $curve_order_speed->order_num == 0 ? 0 : intval($curve_order_speed->read_num_inc / $curve_order_speed->order_num)
                        ]
                    ];
                    $table = new Table([], $rows);

                    $card = new InfoBox('实时订单', '', 'yellow', null, $order_on_num, $table->render());
                    $column->append($card);
                });
            })
            ->row(function (Row $row) {

                //取七天内的数据
                $row->column(12, function (Column $column) {
                    $start_date = Carbon::now()->subDays(7)->toDateString();
                    $end_date = Carbon::now()->toDateString();
                    $rows = FlowChannelStat::query()->groupBy('date')->whereBetween('date', [$start_date, $end_date])->orderByDesc('date')
                        ->select('date')
                        ->selectRaw('sum(pv) as total_pv')
                        ->selectRaw('sum(ip_num) as total_ip_num')
                        ->selectRaw('sum(pv)/sum(ip_num) as pu_rate')
                        ->selectRaw('sum(read_num_incr) as read_num_incr')
                        ->selectRaw('sum(read_num_incr)/sum(pv) as daoda_rate')
                        ->selectRaw('sum(divide_amount) as divide_amount')
                        ->get()->each(function ($row) {
                            $row->amount = OrderReadInfo::query()->whereDate('date', $row->date)->sum('amount');
                            $row->order_num = OrderReadInfo::query()->whereDate('date', $row->date)->distinct()->count('order_id');
                            $row->avg_price = ($row->amount / $row->read_num_incr) * 1000;
                            $row->wanip = round(($row->amount / $row->total_ip_num) * 1000, 2);
                            $row->wanpv = round(($row->amount / $row->total_pv) * 1000, 2);
                        })->toArray();


                    $headers = ['日期', 'PV', 'IP', 'PV/IP', '阅读增量', '到达率', '分成金额', '消耗金额', '今日订单', '订单均价', '千IP', '千PV'];
                    $table = new Table($headers, $rows);
                    $tab = new Tab();
                    $tab->add('七日数据', $table);
                    $column->append($tab);
                });

            })
            ->row(function (Row $row) {


                $row->column(6, function (Column $column) {
                    //取当天所有小时段的PV和IP数据
                    $data = FlowChannelStat::query()->groupBy('hour')
                        ->whereDate('date', Carbon::now()->toDateString())
                        ->selectRaw('sum(pv) as total_pv')
                        ->selectRaw('sum(ip_num) as total_ip_num')
                        ->selectRaw('sum(read_num_incr) as read_num_incr')
                        ->selectRaw('sum(read_num_incr)/sum(pv) as daoda_rate')
                        ->get();
                    $_data = [
                        '阅读增量' => $data->pluck('read_num_incr'),
                        'IP' => $data->pluck('total_ip_num'),
                        'PV' => $data->pluck('total_pv'),
                        '到达率' => $data->pluck('daoda_rate'),
                    ];


                    $box = (new Box('今日趋势', view('admin.chartjs-line', ['data' => $_data]), ''))->style('color:red');
                    $column->append($box);
                });
                $row->column(6, function (Column $column) {

                    $visit_deep = VisitRecord::query()->groupBy('visit_num')
                        ->where('visit_num', '>', 0)
                        ->whereDate('date', Carbon::now()->toDateString())
                        ->selectRaw('count(*) as num,visit_num')
                        ->get();
                    $data_x = $visit_deep->pluck('visit_num');
                    $data_y = [
                        '访问人数' => $visit_deep->pluck('num'),

                    ];
                    $box = (new Box('访问深度', view('admin.chartjs-bar', ['data_x' => $data_x, 'data_y' => $data_y]), ''))->style('color:red');
                    $column->append($box);
                });

            });
    }
}
